// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'xiaogan-gywya',  
  traceUser: true,
})

const db = cloud.database()
var $ = db.command.aggregate
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
  
  const wxContext = cloud.getWXContext()
  // 获取值班表
  if(event.name == 'get_duty'){
    var sche = []
    var duty = {}
    var doctors = {}
    var doct_info = []
    var doct_id = []
    var sche = await db.collection('sche').where({
      sche_month: event.month
    }).get()
    if(sche.data.length == 0){
      return {
        info: null,
        doct_info: null,
      }
    }
    // 获取到每天的值班信息
    var duty = sche.data[0]['sche_day_list']
    // 找到当天值班医生的openid
    doctors = duty.find(item => {return item.index == event.day})
    // 删掉sche中多余的数据
    delete sche.data[0]['sche_day_list']
    // 由于存在一人值当天多个班的情况
    if(doctors != null){
      doct_id.push(doctors['one'])
      doct_id.push(doctors['rota'])
      doct_id.push(doctors['two'])
      doct_id.push(doctors['three'])
      temp = await Promise.all(doct_id.map((item) => {
        return db.collection('user').where({
          _openid: item
        }).get()
      }))
      .then(res => {
        doct_info = res
      })
    }
    return {
      info: sche.data,
      doct_info: doct_info
    }
  }

  //获取用户信息
  else if(event.name == 'get_userinfo'){
    return await db.collection('user').where({
      _openid: wxContext.OPENID,
    }).get()
  }

  else if(event.name == 'get_overview'){
    let temp_result = []
    // 获取病人总数
    let get_count = new Promise((resolve, reject) => {
      db.collection('patient').where({
        patient_del: false
      }).count()
      .then(res => {
        resolve(res.total)
      })
      .catch(res => {
        reject('error')
      })
    })
    //获取今日病房总体情况
    let toady = new Promise((resolve, reject) => {
      db.collection('ward').where({
        ward_submit: false
      }).get()
      .then(res => {
        resolve(res.data[0])
      })
      .catch(res => {
        reject('error')
      })
    })
    // 获取昨日病房总体情况
    let yesterday = new Promise((resolve, reject) => {
      db.collection('ward').where({
        ward_submit: true
      }).orderBy('ward_time', 'desc').limit(1).get()
      .then(res => {
        resolve(res.data[0])
      })
      .catch(res => {
        reject('error')
      })
    })
    // 运行
    await Promise.all([get_count, toady, yesterday]).then(res => {
      temp_result = res
    })
    //获得术前评估人数
    let temp1 = 0
    for(var i in temp_result[2]['ward_bef_asse']){
      temp1 = temp1 + temp_result[2]['ward_bef_asse'][i]
    }
    
    //获取院外等待手术人数
    let temp2 = 0
    for(var i in temp_result[2]['ward_wait_oper']){
      temp2 = temp2 + temp_result[2]['ward_wait_oper'][i]
    }
    
    //获取今日手术字符串
    let temp3 = ''
    for(var i in temp_result[1]['ward_oper']){
      if(temp3 == ''){
        temp3 = temp_result[1]['ward_oper'][i]['name'] + temp_result[1]['ward_oper'][i]['des']
      }
      else{
        temp3 = temp3 + '、' +  temp_result[1]['ward_oper'][i]['name'] + temp_result[1]['ward_oper'][i]['des']
      }
    }
    //获取昨日手术字符串
    let temp4 = ''
    for(var i in temp_result[2]['ward_oper']){
      if(temp4 == ''){
        temp4 = temp_result[2]['ward_oper'][i]['name'] + temp_result[2]['ward_oper'][i]['des']
      }
      else{
        temp4 = temp4 + '、' +  temp_result[2]['ward_oper'][i]['name'] + temp_result[2]['ward_oper'][i]['des']
      }
    }
    //在院术前评估格式转换
    let temp5 = []
    for(var i in temp_result[2]['ward_bef_asse']){
      let temp = {}
      temp['name'] = i
      temp['value'] = temp_result[2]['ward_bef_asse'][i]
      temp5.push(temp)
    }
    //院外等待手术格式转换
    let temp6 = []
    for(var i in temp_result[2]['ward_wait_oper']){
      let temp = {}
      temp['name'] = i
      temp['value'] = temp_result[2]['ward_wait_oper'][i]
      temp6.push(temp)
    }
    
    return{
      patients_num: temp_result[0],
      bed1: temp_result[2]['ward_turnbed'],            //择床
      bed2: temp_result[2]['ward_turnbed_again'],      //则则床
      bed3: temp_result[2]['ward_add_bed'],            //加床
      assessment_num: temp1,                        //术前评估人数
      assessment_detail: temp5,
      wait_oper_num: temp2,                         //等待手术人数
      wait_in_num: temp_result[2]['ward_bed_appoint'].length,  //拟住院人数
      num_900: temp_result[2]['ward_others_hos'].length,       //900
      in_today: temp_result[1]['ward_in'].length,
      out_today: temp_result[1]['ward_out'].length,
      oper_today: temp_result[1]['ward_oper'].length,          //今日手术
      in_yesterday: temp_result[2]['ward_in'].length,
      out_yesterday: temp_result[2]['ward_out'].length,
      oper_yesterday: temp_result[2]['ward_oper'].length,          //今日手术
      in_today_detail: temp_result[1]['ward_in'].join('、'),       //今日入院人员
      in_yesterday_detail: temp_result[2]['ward_in'].join('、'),   //昨日入院人员
      oper_today_detail: temp3,                                 //今日手术详情
      oper_yesterday_detail: temp4,                             //昨日手术详情
      out_today_detail: temp_result[1]['ward_out'].join('、'),            //今日出院人员
      out_yesterday_detail: temp_result[2]['ward_out'].join('、'),        //昨日出院人员
      wait_oper_detail: temp6,             //院外等待手术详情
      wait_in_detail: temp_result[2]['ward_bed_appoint'].join('、'),  //拟住院详情
      detail_900: temp_result[2]['ward_others_hos'].join('、')      //900

    }
    
  }
}

